<template>
    <el-form-item :label="ctx.label.value">
        <div style="border: 1px solid #ccc">
            <Toolbar
                mode="simple"
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
            />
            <Editor
                style="height: 300px"
                mode="simple"
                v-model="viewData.value"
                @onCreated="handleCreated"
                :defaultConfig="editorConfig"
            />
        </div>
    </el-form-item>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { byId } from '../lib/form'
import { onBeforeUnmount, reactive, shallowRef } from 'vue'

// 编辑器实例，必须用 shallowRef
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
const editorRef = shallowRef()
const props = defineProps<{ id: string }>()
const ctx = byId(props.id)
const viewData = reactive({
    value: undefined,
    options: [],
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
</script>

<style scoped lang="scss"></style>
